<template>
  <div class="screen-container">
    <!-- 头部区域 -->
    <div class="header">
      <div class="title">
        <h1>电影实时票房监控系统</h1>
        <div class="update-info">
          <span class="update-time">{{ currentTime }}</span>
          <el-button 
            type="primary" 
            :loading="loading" 
            :disabled="loading"
            @click="handleRefresh"
            size="small"
          >
            <el-icon :class="{ 'rotate': loading }"><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 核心指标区域 -->
    <div class="core-metrics">
      <div v-for="(stat, index) in coreStats" :key="index" class="metric-card">
        <el-icon class="metric-icon"><component :is="stat.icon" /></el-icon>
        <div class="metric-info">
          <div class="metric-title">{{ stat.title }}</div>
          <div class="metric-value">{{ stat.value }}</div>
          <div class="metric-trend">
            <el-icon :class="['trend-icon', stat.trend > 0 ? 'up' : stat.trend < 0 ? 'down' : '']">
              <ArrowUp v-if="stat.trend > 0" />
              <ArrowDown v-if="stat.trend < 0" />
            </el-icon>
            <span>{{ stat.details }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：实时排名 -->
      <div class="ranking-section">
        <div class="section-header">
          <div class="section-title">
            <h2>实时排名</h2>
          </div>
          <el-radio-group v-model="rankingType" size="small">
            <el-radio-button value="boxOffice">按票房</el-radio-button>
            <el-radio-button value="shows">按场次</el-radio-button>
          </el-radio-group>
        </div>
        <div class="ranking-table-container" ref="tableContainer">
          <el-table
            ref="rankingTable"
            :data="movieRankings"
            :header-cell-style="tableHeaderStyle"
            class="ranking-table"
            stripe
            :height="tableHeight"
          >
            <el-table-column type="index" label="排名" width="80" align="center" fixed="left">
              <template #default="scope">
                <span class="ranking-number">
                  {{ scope.$index + 1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="movie_name" label="电影名称" min-width="180">
              <template #default="{ row }">
                <span class="movie-name">{{ row.movie_name }}</span>
              </template>
            </el-table-column>
            <el-table-column 
              :prop="rankingType === 'boxOffice' ? 'sum_box_desc' : 'show_count'" 
              :label="rankingType === 'boxOffice' ? '累计票房(万)' : '排片场次'" 
              sortable 
              min-width="140"
              align="center"
            >
              <template #default="{ row }">
                <span :class="rankingType === 'boxOffice' ? 'box-office' : 'show-count'">
                  {{ formatNumber(rankingType === 'boxOffice' ? row.sum_box_desc : row.show_count) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="show_count_rate" label="排片占比" min-width="180" align="center">
              <template #default="{ row }">
                <el-progress 
                  :percentage="row.show_count_rate" 
                  :format="(val) => val.toFixed(1) + '%'"
                  :color="getProgressColor(row.show_count_rate/100)"
                  :stroke-width="8"
                />
              </template>
            </el-table-column>
            <el-table-column prop="split_box_rate" label="分账比例" min-width="180" align="center">
              <template #default="{ row }">
                <el-progress 
                  :percentage="row.split_box_rate" 
                  :format="(val) => val.toFixed(1) + '%'"
                  :color="getProgressColor(row.split_box_rate/100)"
                  :stroke-width="8"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 右侧：数据分析 -->
      <div class="analysis-section">
        <!-- 票房/排片分布饼图 -->
        <div class="chart-box">
          <div class="section-header">
            <div class="section-title">
              <h2>{{ rankingType === 'boxOffice' ? '票房分布' : '排片分布' }}</h2>
            </div>
          </div>
          <div class="chart-container">
            <v-chart :option="pieOption" autoresize />
          </div>
        </div>

        <!-- 市场分析 -->
        <div class="market-analysis">
          <div class="section-header">
            <div class="section-title">
              <h2>市场分析</h2>
            </div>
          </div>
          <div class="analysis-grid">
            <div class="analysis-item">
              <div class="item-header">市场状况</div>
              <div class="item-content">{{ getMarketStatus() }}</div>
            </div>
            <div class="analysis-item">
              <div class="item-header">{{ rankingType === 'boxOffice' ? '档期表现' : '排片表现' }}</div>
              <div class="item-content">{{ getMarketPerformance() }}</div>
            </div>
            <div class="analysis-item">
              <div class="item-header">竞争格局</div>
              <div class="item-content">{{ getCompetitionStatus() }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.screen-container {
  width: 100vw;
  height: 100vh;
  background: #0a1929;
  color: #fff;
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  font-family: "Microsoft YaHei", -apple-system, sans-serif;
}

.header {
  padding: 0;
  height: 48px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 8px;
}

.title h1 {
  font-size: 28px;
  margin: 0;
  color: #00b7ff;
  font-weight: 500;
  letter-spacing: 2px;
  text-shadow: 0 0 10px rgba(0, 183, 255, 0.3);
}

.update-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.update-time {
  color: #7eb9ff;
  font-size: 14px;
  font-family: "Consolas", monospace;
  letter-spacing: 0.8px;
  background: rgba(14, 42, 71, 0.8);
  padding: 6px 12px;
  border-radius: 4px;
  border: 1px solid rgba(30, 144, 255, 0.2);
  box-shadow: 0 0 10px rgba(30, 144, 255, 0.1);
}

:deep(.el-button--small) {
  padding: 8px 16px;
  font-size: 13px;
  height: 32px;
}

:deep(.el-button--small .el-icon) {
  font-size: 15px;
  margin-right: 4px;
}

.core-metrics {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-top: 4px;
  height: 90px;
}

.metric-card {
  background: rgba(13, 36, 62, 0.8);
  border-radius: 6px;
  padding: 16px 20px;
  border: 1px solid rgba(30, 144, 255, 0.15);
  box-shadow: 0 0 15px rgba(0, 183, 255, 0.1);
  display: flex;
  align-items: center;
  gap: 12px;
}

.metric-icon {
  font-size: 24px;
  color: #00b7ff;
  text-shadow: 0 0 8px rgba(0, 183, 255, 0.4);
}

.metric-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.metric-title {
  font-size: 12px;
  color: #888;
}

.metric-value {
  font-size: 26px;
  font-weight: 500;
  color: #fff;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
  font-family: "DIN", "Arial", sans-serif;
}

.metric-trend {
  font-size: 11px;
  color: #888;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  overflow: hidden;
  height: calc(100vh - 160px);
  margin-bottom: 8px;
}

.ranking-section {
  flex: 2.2;
  background: rgba(13, 36, 62, 0.8);
  border-radius: 6px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(30, 144, 255, 0.15);
  box-shadow: 0 0 20px rgba(0, 183, 255, 0.1);
  backdrop-filter: blur(10px);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid rgba(30, 144, 255, 0.2);
  min-height: 24px;
}

.section-header h2 {
  font-size: 16px;
  color: #7eb9ff;
  font-weight: 500;
  letter-spacing: 1px;
  text-shadow: 0 0 8px rgba(0, 183, 255, 0.3);
}

.analysis-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-width: 320px;
  max-width: 380px;
}

.chart-box {
  flex: 0.8;
  background: rgba(13, 36, 62, 0.8);
  border-radius: 6px;
  padding: 16px;
  border: 1px solid rgba(30, 144, 255, 0.15);
  box-shadow: 0 0 20px rgba(0, 183, 255, 0.1);
  display: flex;
  flex-direction: column;
  overflow: visible;
  margin-bottom: 4px;
  min-height: 200px;
}

.chart-container {
  flex: 1;
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.market-analysis {
  flex: 1.4;
  background: rgba(13, 36, 62, 0.8);
  border-radius: 6px;
  padding: 16px;
  border: 1px solid rgba(30, 144, 255, 0.15);
  box-shadow: 0 0 20px rgba(0, 183, 255, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 280px;
  margin-bottom: 8px;
}

.analysis-grid {
  display: grid;
  gap: 16px;
  grid-template-rows: repeat(3, 1fr);
  height: calc(100% - 36px);
  padding: 8px 0;
}

.analysis-item {
  background: rgba(14, 42, 71, 0.6);
  border-radius: 6px;
  padding: 16px 20px;
  border: 1px solid rgba(30, 144, 255, 0.15);
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 72px;
}

.item-header {
  font-size: 14px;
  color: #7eb9ff;
  margin-bottom: 10px;
  letter-spacing: 0.5px;
}

.item-content {
  font-size: 15px;
  color: #fff;
  font-weight: normal;
  line-height: 1.6;
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.1);
}

:deep(.el-table) {
  background: transparent !important;
  font-family: "Microsoft YaHei", -apple-system, sans-serif;
  border: none !important;
  overflow: hidden !important;
}

:deep(.el-table::before) {
  display: none;
}

:deep(.el-table th) {
  background: rgba(14, 42, 71, 0.9) !important;
  color: #7eb9ff !important;
  font-weight: 500;
  font-size: 14px;
  border-bottom: 1px solid rgba(30, 144, 255, 0.2) !important;
  padding: 8px 0;
  height: 40px;
}

:deep(.el-table td) {
  background: rgba(13, 36, 62, 0.6) !important;
  border-bottom: 1px solid rgba(30, 144, 255, 0.1) !important;
  font-size: 14px;
  color: #fff !important;
  padding: 12px 0;
  height: 44px;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: rgba(14, 42, 71, 0.4) !important;
}

:deep(.el-table__body tr:hover td) {
  background: rgba(30, 144, 255, 0.15) !important;
}

:deep(.el-table__body tr) {
  animation: tableRowFadeIn 0.5s ease-out;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background: rgba(30, 144, 255, 0.2) !important;
}

:deep(.el-table__row) {
  background: transparent !important;
}

:deep(.el-table__header-wrapper) {
  border-bottom: 2px solid rgba(30, 144, 255, 0.2);
}

:deep(.el-table__fixed-right-patch) {
  background: rgba(14, 42, 71, 0.9) !important;
}

:deep(.el-table__fixed-header-wrapper) {
  background: rgba(14, 42, 71, 0.9) !important;
}

:deep(.el-table__fixed, .el-table__fixed-right) {
  background: transparent !important;
  &::before {
    display: none;
  }
}

:deep(.el-table__fixed-body-wrapper) {
  background: transparent !important;
}

.box-office, .show-count {
  color: #00b7ff;
  font-weight: 500;
  font-size: 15px;
  text-shadow: 0 0 8px rgba(0, 183, 255, 0.3);
  font-family: "DIN", "Arial", sans-serif;
  background: rgba(0, 183, 255, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

:deep(.el-progress) {
  margin: 0;
  width: 100%;
}

:deep(.el-progress-bar__outer) {
  height: 8px !important;
  background: rgba(14, 42, 71, 0.8) !important;
  border-radius: 4px !important;
}

:deep(.el-progress-bar__inner) {
  border-radius: 4px !important;
  box-shadow: 0 0 8px rgba(0, 183, 255, 0.3);
  transition: all 0.3s ease-in-out;
}

:deep(.el-progress__text) {
  color: #7eb9ff !important;
  font-size: 12px !important;
  font-family: "DIN", "Arial", sans-serif;
  text-shadow: 0 0 8px rgba(0, 183, 255, 0.2);
  margin-left: 6px !important;
}

:deep(.el-table .cell) {
  line-height: 24px;
}

.ranking-number {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 4px;
  background: rgba(0, 183, 255, 0.15);
  color: #00b7ff;
  font-family: "DIN", "Arial", sans-serif;
  font-weight: 500;
  text-shadow: 0 0 8px rgba(0, 183, 255, 0.3);
}

:deep(.el-radio-group) {
  display: flex;
  align-items: center;
}

:deep(.el-radio-button) {
  margin-right: -1px;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px 0 0 4px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 4px 4px 0;
}

:deep(.el-radio-button__inner) {
  background: rgba(14, 42, 71, 0.8);
  border-color: rgba(30, 144, 255, 0.3);
  color: #7eb9ff;
  font-size: 13px;
  text-shadow: 0 0 8px rgba(0, 183, 255, 0.2);
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background: #00b7ff;
  border-color: #00b7ff;
  color: #fff;
  box-shadow: 0 0 10px rgba(0, 183, 255, 0.4);
}

.info-icon {
  color: #888;
  cursor: pointer;
  font-size: 14px;
}

:deep(.echarts) {
  width: 100% !important;
  height: 100% !important;
  min-height: 180px;
  transform: scale(1.1);
  transform-origin: center center;
}

/* 添加数据更新过渡效果 */
.metric-value,
.box-office,
.show-count,
:deep(.el-progress-bar__inner),
:deep(.el-progress__text) {
  transition: all 0.3s ease-in-out;
}

/* 表格行过渡效果 */
:deep(.el-table__body tr) {
  transition: all 0.3s ease-in-out;
}

/* 图表过渡效果 */
.chart-container {
  transition: opacity 0.3s ease-in-out;
}

/* 加载状态透明度控制 */
.loading {
  opacity: 0.6;
  pointer-events: none;
}

/* 添加表格加载遮罩样式 */
:deep(.el-loading-mask) {
  background-color: rgba(30, 30, 30, 0.8) !important;
}

:deep(.el-loading-spinner .path) {
  stroke: #40a9ff !important;
}

.rotate {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 添加电影名称样式 */
.movie-name {
  color: #fff;
  font-size: 14px;
  font-weight: normal;
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

:deep(.el-table__row:hover) .movie-name {
  background: rgba(30, 144, 255, 0.1);
  color: #00b7ff;
}

/* 添加表格容器样式 */
.ranking-table-container {
  position: relative;
  flex: 1;
  overflow: hidden;
}

:deep(.el-table__body-wrapper) {
  overflow-y: hidden !important;
  scrollbar-width: none;
  -ms-overflow-style: none;
  &::-webkit-scrollbar {
    display: none;
  }
}

:deep(.el-table__body) {
  transition: none !important;
}

:deep(.el-table__body tr) {
  transition: none !important;
}

@keyframes tableRowFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

:deep(.el-table__body tr) {
  animation: tableRowFadeIn 0.5s ease-out;
}

:deep(.el-table__row) {
  transition: all 0.3s ease-in-out;
}

:deep(.el-table__row:hover) {
  background: rgba(30, 144, 255, 0.15) !important;
  transform: scale(1.01);
}
</style>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted, reactive } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import { LegendComponent, TooltipComponent, TitleComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { ElMessage } from 'element-plus'
import { Refresh, ArrowUp, ArrowDown, Tickets, VideoCamera, Timer, DataLine, InfoFilled } from '@element-plus/icons-vue'
import { getCleanedMovies } from '@/api/movie'

// 注册必要的组件
use([CanvasRenderer, PieChart, LegendComponent, TooltipComponent, TitleComponent])

// 数据定义
const loading = ref(false)
const movieRankings = ref([])
const coreStats = ref([])
const pieOption = ref({})
const rankingType = ref('boxOffice')
const currentTime = ref('')
const isFirstLoad = ref(true)
const tempData = ref(null)
const currentIndex = ref(0)
const scrollTimer = ref(null)
const timeTimer = ref(null)

// 表格样式常量
const tableHeaderStyle = {
  background: 'transparent',
  color: '#888',
  fontWeight: 'normal',
  borderBottom: '1px solid #333'
}

// 获取进度条颜色
const getProgressColor = (value) => {
  if (value >= 0.8) return '#67C23A'
  if (value >= 0.6) return '#409EFF'
  if (value >= 0.4) return '#E6A23C'
  return '#F56C6C'
}

// 市场分析方法
const getMarketStatus = () => {
  if (rankingType.value === 'boxOffice') {
    const totalBoxOffice = movieRankings.value.reduce((sum, movie) => sum + parseFloat(movie.sum_box_desc || 0), 0)
    if (totalBoxOffice > 2000000) return '市场火爆，总票房超20亿'
    if (totalBoxOffice > 1000000) return '市场活跃，总票房超10亿'
    return '市场平稳'
  } else {
    const totalShows = movieRankings.value.reduce((sum, movie) => sum + movie.show_count, 0)
    if (totalShows > 300000) return '排片活跃，总场次超30万'
    if (totalShows > 200000) return '排片良好，总场次超20万'
    return '排片平稳'
  }
}

const getMarketPerformance = () => {
  if (!movieRankings.value.length) return '暂无数据'
  
  if (rankingType.value === 'boxOffice') {
    const avgBoxOffice = movieRankings.value.reduce((sum, movie) => sum + parseFloat(movie.sum_box_desc || 0), 0) / movieRankings.value.length
    if (avgBoxOffice > 100000) return '头部影片表现强势'
    if (avgBoxOffice > 50000) return '档期表现良好'
    return '档期表现一般'
  } else {
    const avgShows = movieRankings.value.reduce((sum, movie) => sum + movie.show_count, 0) / movieRankings.value.length
    if (avgShows > 30000) return '排片集中度高'
    if (avgShows > 15000) return '排片分布均衡'
    return '排片较为分散'
  }
}

const getCompetitionStatus = () => {
  if (!movieRankings.value.length) return '暂无数据'
  
  if (rankingType.value === 'boxOffice') {
    const totalBoxOffice = movieRankings.value.reduce((sum, movie) => sum + parseFloat(movie.sum_box_desc || 0), 0)
    const top3BoxOffice = movieRankings.value.slice(0, 3).reduce((sum, movie) => sum + parseFloat(movie.sum_box_desc || 0), 0)
    const concentration = (top3BoxOffice / totalBoxOffice) * 100
    
    if (concentration > 80) return '市场集中度高'
    if (concentration > 60) return '市场较为集中'
    return '市场分散'
  } else {
    const totalShows = movieRankings.value.reduce((sum, movie) => sum + movie.show_count, 0)
    const top3Shows = movieRankings.value.slice(0, 3).reduce((sum, movie) => sum + movie.show_count, 0)
    const concentration = (top3Shows / totalShows) * 100
    
    if (concentration > 70) return '排片高度集中'
    if (concentration > 50) return '排片较为集中'
    return '排片较为分散'
  }
}

// 格式化数字（添加千位分隔符）
const formatNumber = (num) => {
  if (!num) return '0'
  return Number(num).toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}

// 修改格式化时间的方法
const formatDateTime = (date = new Date()) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
}

// 添加更新时间的方法
const updateCurrentTime = () => {
  currentTime.value = formatDateTime()
}

// 获取数据
const fetchData = async () => {
  if (!isFirstLoad.value && !loading.value) {
    loading.value = true
  }
  
  try {
    const movieResponse = await getCleanedMovies()
    if (movieResponse && movieResponse.data) {
      const movies = movieResponse.data
      
      // 处理新数据
      const newRankings = movies
        .map(movie => ({
          movie_name: movie.movie_name,
          sum_box_desc: parseFloat(movie.sum_box_desc?.replace(/[^0-9.]/g, '') || '0'),
          show_count: parseInt(movie.show_count) || 0,
          show_count_rate: parseFloat(movie.show_count_rate?.replace(/[^0-9.]/g, '') || '0'),
          split_box_rate: parseFloat(movie.split_box_rate?.replace(/[^0-9.]/g, '') || '0'),
          release_info: movie.release_info
        }))
        .sort((a, b) => rankingType.value === 'boxOffice' ? 
          b.sum_box_desc - a.sum_box_desc : 
          b.show_count - a.show_count)

      // 计算新的统计数据
      const totalBoxOffice = newRankings.reduce((sum, movie) => sum + movie.sum_box_desc, 0)
      const totalShows = newRankings.reduce((sum, movie) => sum + movie.show_count, 0)
      const top3BoxOffice = newRankings.slice(0, 3).reduce((sum, movie) => sum + movie.sum_box_desc, 0)
      const top3Shows = newRankings.slice(0, 3).reduce((sum, movie) => sum + movie.show_count, 0)
      const boxOfficeConcentration = (top3BoxOffice / totalBoxOffice * 100).toFixed(1)
      const showingConcentration = (top3Shows / totalShows * 100).toFixed(1)

      // 准备新的核心统计数据
      const newCoreStats = [
        { 
          title: '总票房', 
          value: formatNumber(totalBoxOffice) + '万',
          icon: 'Tickets',
          trend: 1,
          details: `日均票房：${formatNumber(totalBoxOffice / 7)}万`
        },
        { 
          title: '总场次', 
          value: formatNumber(totalShows),
          icon: 'VideoCamera',
          trend: 0,
          details: `场均票房：${formatNumber(totalBoxOffice / totalShows)}万`
        },
        { 
          title: '票房集中度', 
          value: boxOfficeConcentration + '%',
          icon: 'Timer',
          trend: 1,
          details: `前三大影片占比`
        },
        { 
          title: '排片集中度', 
          value: showingConcentration + '%',
          icon: 'DataLine',
          trend: -1,
          details: `共${movies.length}部影片`
        }
      ]

      // 使用 nextTick 批量更新数据
      nextTick(() => {
        movieRankings.value = newRankings
        coreStats.value = newCoreStats
        updateCurrentTime()
        updateCharts()
        isFirstLoad.value = false
      })
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    if (!isFirstLoad.value) {
      ElMessage.error('获取数据失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 更新图表数据
const updateCharts = () => {
  if (!movieRankings.value.length) return

  const top5Movies = movieRankings.value.slice(0, 5)
  const totalValue = rankingType.value === 'boxOffice' 
    ? top5Movies.reduce((sum, movie) => sum + movie.sum_box_desc, 0)
    : top5Movies.reduce((sum, movie) => sum + movie.show_count, 0)
  
  const pieData = top5Movies.map(movie => ({
    name: movie.movie_name,
    value: rankingType.value === 'boxOffice' ? movie.sum_box_desc : movie.show_count,
    percentage: ((rankingType.value === 'boxOffice' ? movie.sum_box_desc : movie.show_count) / totalValue * 100).toFixed(1)
  }))

  pieOption.value = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      formatter: params => {
        const unit = rankingType.value === 'boxOffice' ? '万' : '场'
        return `${params.name}<br/>${params.data.percentage}%`
      },
      backgroundColor: 'rgba(13, 36, 62, 0.9)',
      borderColor: 'rgba(30, 144, 255, 0.2)',
      textStyle: {
        color: '#fff',
        fontSize: 14
      }
    },
    color: ['#00b7ff', '#00ffb3', '#fff000', '#ff7e00', '#ff0000'],
    series: [
      {
        type: 'pie',
        radius: ['30%', '70%'],
        center: ['50%', '55%'],
        startAngle: 225,
        endAngle: -45,
        itemStyle: {
          borderRadius: 4,
          borderColor: '#0a1929',
          borderWidth: 2,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 183, 255, 0.3)'
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        emphasis: {
          scale: false,
          focus: 'none',
          itemStyle: {
            shadowBlur: 20,
            shadowColor: 'rgba(0, 183, 255, 0.5)'
          }
        },
        data: pieData
      }
    ]
  }
}

// 监听排序方式变化
watch(rankingType, () => {
  movieRankings.value = [...movieRankings.value].sort((a, b) => 
    rankingType.value === 'boxOffice' ? 
      b.sum_box_desc - a.sum_box_desc : 
      b.show_count - a.show_count
  )
  // 更新图表和分析
  updateCharts()
})

// 表格滚动相关变量
const rankingTable = ref(null)
const tableContainer = ref(null)
const tableHeight = ref(500)

// 表格滚动函数
const startTableScroll = () => {
  if (scrollTimer.value) clearInterval(scrollTimer.value)
  
  scrollTimer.value = setInterval(() => {
    if (!rankingTable.value || !movieRankings.value.length) return
    
    const tbody = rankingTable.value.$el.querySelector('.el-table__body-wrapper')
    if (!tbody) return
    
    const rowHeight = 44
    const maxScroll = tbody.scrollHeight - tbody.clientHeight
    
    if (tbody.scrollTop >= maxScroll) {
      tbody.scrollTop = 0
    } else {
      tbody.scrollTop = tbody.scrollTop + rowHeight
    }
  }, 1000)
}

// 组件挂载
onMounted(() => {
  fetchData()
  updateCurrentTime()
  timeTimer.value = setInterval(updateCurrentTime, 1000)
  
  nextTick(() => {
    updateTableHeight()
    startTableScroll()
  })
  
  window.addEventListener('resize', updateTableHeight)
})

// 组件卸载
onUnmounted(() => {
  if (timeTimer.value) {
    clearInterval(timeTimer.value)
    timeTimer.value = null
  }
  if (scrollTimer.value) {
    clearInterval(scrollTimer.value)
    scrollTimer.value = null
  }
  window.removeEventListener('resize', updateTableHeight)
})

// 监听数据变化
watch(movieRankings, () => {
  if (rankingTable.value) {
    const tbody = rankingTable.value.$el.querySelector('.el-table__body-wrapper')
    if (tbody) {
      tbody.scrollTop = 0
      nextTick(() => {
        startTableScroll()
      })
    }
  }
}, { deep: true })

// 更新表格高度
const updateTableHeight = () => {
  if (rankingTable.value && tableContainer.value) {
    const containerHeight = tableContainer.value.clientHeight
    const headerHeight = 40
    tableHeight.value = containerHeight - headerHeight
  }
}

// 刷新数据方法
const handleRefresh = () => {
  if (!loading.value) {
    fetchData()
  }
}

// 在 script setup 中的 data 部分
const tableData = reactive({
  currentIndex: 0,
  scrollTimer: null,
  rowHeight: 44,
  scrollInterval: 1000
})

// 在 methods 部分
const scrollOneRow = () => {
  if (!rankingTable.value || !movieRankings.value.length) return
  
  const tbody = rankingTable.value.$el.querySelector('.el-table__body-wrapper')
  if (!tbody) return
  
  // 计算下一行索引
  const nextIndex = (tableData.currentIndex + 1) % movieRankings.value.length
  
  // 执行滚动
  tbody.scrollTo({
    top: nextIndex * tableData.rowHeight,
    behavior: nextIndex === 0 ? 'instant' : 'smooth'
  })
  
  // 更新当前索引
  tableData.currentIndex = nextIndex
}

const startScroll = () => {
  stopScroll()
  tableData.scrollTimer = setInterval(scrollOneRow, tableData.scrollInterval)
}

const stopScroll = () => {
  if (tableData.scrollTimer) {
    clearInterval(tableData.scrollTimer)
    tableData.scrollTimer = null
  }
}
</script>

